<template>
  <div>
    <n-card title="公告管理">
      <template #header-extra>
        <n-button type="primary" @click="handleCreate">
          <template #icon>
            <n-icon><AddOutline /></n-icon>
          </template>
          发布公告
        </n-button>
      </template>

      <n-data-table
        :columns="columns"
        :data="notifications"
        :pagination="pagination"
        :loading="loading"
      />
    </n-card>

    <n-modal v-model:show="modalVisible" preset="dialog" :title="isEdit ? '编辑公告' : '发布公告'" style="width: 600px">
      <n-form :model="formValue" ref="formRef" label-placement="left" label-width="80">
        <n-form-item label="标题">
          <n-input v-model:value="formValue.title" placeholder="请输入标题" />
        </n-form-item>
        <n-form-item label="类型">
          <n-select v-model:value="formValue.type" :options="typeOptions" />
        </n-form-item>
        <n-form-item label="内容">
          <n-input
            v-model:value="formValue.content"
            type="textarea"
            placeholder="请输入内容"
            :rows="5"
          />
        </n-form-item>
      </n-form>
      <template #action>
        <n-space>
          <n-button @click="modalVisible = false">取消</n-button>
          <n-button type="primary" @click="handleSubmit">确定</n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script setup>
import { ref, reactive, h, onMounted } from 'vue'
import { NButton, NSpace, NTag, NPopconfirm } from 'naive-ui'
import { useUserStore } from '@/stores/user'
import { getNotificationList, createNotification, updateNotification, deleteNotification } from '@/api/notification'
import { AddOutline } from '@vicons/ionicons5'

const userStore = useUserStore()

const loading = ref(false)
const notifications = ref([])
const modalVisible = ref(false)
const isEdit = ref(false)
const formRef = ref(null)

const formValue = reactive({
  id: null,
  title: '',
  type: 'SYSTEM',
  content: ''
})

const pagination = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 30],
  onChange: (page) => {
    pagination.page = page
    loadNotifications()
  },
  onUpdatePageSize: (pageSize) => {
    pagination.pageSize = pageSize
    pagination.page = 1
    loadNotifications()
  }
})

const typeOptions = [
  { label: '系统通知', value: 'SYSTEM' },
  { label: '活动通知', value: 'ACTIVITY' },
  { label: '需求通知', value: 'DEMAND' }
]

const columns = [
  { title: '标题', key: 'title' },
  { 
    title: '类型', 
    key: 'type',
    render: (row) => {
      const typeMap = { SYSTEM: 'info', ACTIVITY: 'success', DEMAND: 'warning' }
      const textMap = { SYSTEM: '系统', ACTIVITY: '活动', DEMAND: '需求' }
      return h(NTag, { type: typeMap[row.type] }, { default: () => textMap[row.type] })
    }
  },
  { 
    title: '内容', 
    key: 'content',
    ellipsis: {
      tooltip: true
    }
  },
  { 
    title: '发布时间', 
    key: 'createTime',
    render: (row) => new Date(row.createTime).toLocaleString('zh-CN')
  },
  {
    title: '操作',
    key: 'actions',
    render: (row) => {
      return h(NSpace, null, {
        default: () => [
          h(NButton, {
            size: 'small',
            onClick: () => handleEdit(row)
          }, { default: () => '编辑' }),
          h(NPopconfirm, {
            onPositiveClick: () => handleDelete(row.id)
          }, {
            default: () => '确定删除此公告吗？',
            trigger: () => h(NButton, {
              size: 'small',
              type: 'error'
            }, { default: () => '删除' })
          })
        ]
      })
    }
  }
]

const loadNotifications = async () => {
  loading.value = true
  try {
    const res = await getNotificationList({
      page: pagination.page,
      size: pagination.pageSize
    })
    notifications.value = res.data.records || []
    pagination.itemCount = res.data.total || 0
  } catch (error) {
    console.error('加载公告失败:', error)
  } finally {
    loading.value = false
  }
}

const handleCreate = () => {
  isEdit.value = false
  Object.assign(formValue, {
    id: null,
    title: '',
    type: 'SYSTEM',
    content: ''
  })
  modalVisible.value = true
}

const handleEdit = (row) => {
  isEdit.value = true
  Object.assign(formValue, row)
  modalVisible.value = true
}

const handleSubmit = async () => {
  try {
    const data = {
      ...formValue,
      publisherId: userStore.userId
    }
    
    if (isEdit.value) {
      await updateNotification(formValue.id, data)
      window.$message?.success('更新成功')
    } else {
      await createNotification(data)
      window.$message?.success('发布成功')
    }
    
    modalVisible.value = false
    loadNotifications()
  } catch (error) {
    console.error('操作失败:', error)
  }
}

const handleDelete = async (id) => {
  try {
    await deleteNotification(id)
    window.$message?.success('删除成功')
    loadNotifications()
  } catch (error) {
    console.error('删除失败:', error)
  }
}

onMounted(() => {
  loadNotifications()
})
</script>

